<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" ref="dataFormRef" @keyup.enter.native="getDataList(1)">
      <el-form-item>
        单位：
        <el-select size="mini" v-model="dataForm.unit" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        选择过滤：
        <el-select size="mini" v-model="dataForm.selectField" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in selectFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="dataForm.selectValue" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <!-- profit = salePrice - wholesalePrice,
       profitRate = (salePrice - wholesalePrice)/salePrice * 100 -->
      <el-form-item>
        库存/价格/毛利过滤：
        <el-select size="mini" v-model="dataForm.priceField" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in priceFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="dataForm.priceFormula" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in priceFormulas" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.priceValue" clearable type="number" placeholder="库存/价格/毛利"
          @blur="getDataList(1)" @clear="getDataList(1)"></el-input>
      </el-form-item>
      <el-form-item>
        查询过滤：
        <el-select size="mini" v-model="dataForm.queryField" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in queryFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.key" placeholder="参数名" clearable @blur="getDataList(1)"
          @clear="getDataList(1)"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="success" @click="getDataList(1)" icon="el-icon-search">查询</el-button>
        <el-button @click="resetForm" size="mini" type="warning" icon="el-icon-refresh-left">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="3">
        <el-card class="box-card">
          <el-input placeholder="输入关键字进行过滤" size="mini" v-model="filterText" clearable>
          </el-input>
          <el-tree class="filter-tree" ref="tree" node-key="id" :data="treeData" :props="defaultProps"
            :filter-node-method="filterNode" @node-click="handleNodeClick" default-expand-all>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="21">
        <el-card class="box-card">
          <el-form>
            <el-form-item>
              <el-button size="mini" v-if="isAuth('base:baseproduct:save')" type="primary" @click="addOrUpdateHandle()"
                icon="el-icon-plus">新增</el-button>
              <el-button size="mini" v-if="isAuth('base:baseproduct:delete')" type="danger" @click="deleteHandle()"
                icon="el-icon-delete" :disabled="dataListSelections.length <= 0">删除</el-button>
              <el-button-group style="margin: 0 10px;">
                <el-button size="mini" v-if="isAuth('base:baseproduct:export')" type="success" @click="exportData(1)"
                  class="iconfont icon-topsales">导出基本信息</el-button>
                <el-button size="mini" v-if="isAuth('base:baseproduct:export')" type="success" @click="exportData(2)"
                  class="iconfont icon-topsales">导出全部属性</el-button>
               </el-button-group>
              <el-button size="mini" v-if="isAuth('base:baseproduct:import')" type="warning" @click="handleImport()"
                  class="iconfont icon-skip">导入基本信息</el-button>
              <el-button size="mini" v-if="isAuth('base:baseproduct:download')" type="info" @click="downloadDataHandle()" :disabled="downButtonDisabled"
                 class="iconfont icon-download">数据下载<span class="new-data" :class="downHide">{{downCount}}</span></el-button>
              <el-progress :text-inside="true" :hidden="progressHidden" :stroke-width="26" :percentage="percentage"></el-progress>
              <el-button size="mini" style="margin-left: 10px;" v-if="isAuth('base:baseproduct:upprice')" type="info" @click="handleUpPrice()"
                  class="iconfont icon-rising1">涨价<span class="new-data" :class="upPriceHide">{{upPrice}}</span></el-button>
              <el-button size="mini" style="margin-left: 10px;" v-if="isAuth('base:baseproduct:downprice')" type="info" @click="handleDownPrice()"
                  class="iconfont icon-falling">降价<span class="new-data" :class="downPriceHide">{{downPrice}}</span></el-button>
            </el-form-item>
            <el-form-item>
              <el-dialog title="导入药品数据" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
                    <el-upload
                        ref="upload"
                        :limit="1"
                        accept=".xlsx, .xls"
                        :headers="upload.headers"
                        :before-upload="beforeUpload"
                        :action="upload.url"
                        :disabled="upload.isUploading"
                        :on-progress="handleFileUploadProgress"
                        :on-success="handleFileSuccess"
                        :auto-upload="false"
                        :file-list="excelList"
                        :on-remove="onRemoveDr"
                        :on-change="onChangeDr"
                        drag
                      >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                          将文件拖到此处，或
                          <em>点击上传</em>
                        </div>
                        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
                      </el-upload>
                      <el-button size="mini" type="success" @click="downloadImportTemplate">下载模板</el-button>
                      <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitFileForm">导 入</el-button>
                        <el-button @click="cancelFileForm">取 消</el-button>
                      </div>
                  </el-dialog>
            </el-form-item>
          </el-form>
          <el-table :data="dataList" size="mini" v-loading="dataListLoading" @selection-change="selectionChangeHandle"
            style="width: 100%; min-height: 520px;" @cell-click="tableDbEdit" @cell-dblclick="tableDbEdit"
            :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
            <el-table-column type="selection" header-align="center" align="center" width="50">
            </el-table-column>
            <!-- <el-table-column type="index" header-align="center" align="center" label="#" width="40">
            </el-table-column> -->
            <el-table-column prop="productCode" header-align="center" align="center" label="产品编码" width="100" >
              <!-- <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.productCode" v-if="showInput == `productCode${scope.row.productId}`"
                  @blur='blurInput(scope.row, "productCode", scope.row.productCode)' v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.productCode}}</span>
              </template> -->
            </el-table-column>
            <el-table-column prop="productName" header-align="center" align="center" label="产品名称" width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.productName" v-if="showInput == `productName${scope.row.productId}`"
                  @blur='blurInput(scope.row, "productName", scope.row.productName)' v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.productName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="standard" header-align="center" align="center" label="规格" width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.standard" v-if="showInput == `standard${scope.row.productId}`"
                  @blur='blurInput(scope.row, "standard", scope.row.standard)' v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.standard}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="unit" header-align="center" align="center" label="单位">
              <template slot-scope="scope">
               <!-- <el-input size="mini" v-model="scope.row.unit" v-if="showInput == `unit${scope.row.productId}`"
                  @blur='blurInput(scope.row, "unit", scope.row.unit)' v-focus>
                </el-input> -->
                <el-select size="mini" v-model="scope.row.unit" v-if="showInput == `unit${scope.row.productId}`"
                  @change='blurInput(scope.row, "unit", scope.row.unit)' v-focus placeholder="请选择">
                  <el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.label">
                  </el-option>
                </el-select>
                <span v-else style="text-decoration:none;">{{scope.row.unit}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" header-align="center" align="center" label="是否可用">
              <template slot-scope="scope">
                <el-switch size="mini" v-model="scope.row.status" @change="updateStatusHandle(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="salePrice" header-align="center" align="center" label="售价" width="90">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.salePrice" v-if="showInput == `salePrice${scope.row.productId}`"
                  @blur='blurInput(scope.row, "salePrice", scope.row.salePrice)' type="number" v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.salePrice}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="totalStorage" header-align="center" align="center" label="总库存">
              <!-- <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.totalStorage" v-if="showInput == `totalStorage${scope.row.productId}`"
                  @blur='blurInput(scope.row, "totalStorage", scope.row.totalStorage)' v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.totalStorage}}</span>
              </template> -->
            </el-table-column>
            <el-table-column prop="categoryName" header-align="center" align="center" label="类别名称" width="90" show-overflow-tooltip>
              <!-- <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.categoryName" v-if="showInput == `categoryName${scope.row.productId}`"
                  @blur='blurInput(scope.row, "categoryName", scope.row.categoryName)' v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.categoryName}}</span>
              </template> -->
            </el-table-column>
            <el-table-column prop="barCode" header-align="center" align="center" label="条形码" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.barCode" v-if="showInput == `barCode${scope.row.productId}`"
                  @blur='blurInput(scope.row, "barCode", scope.row.barCode)' v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.barCode}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="expiryDay" header-align="center" align="center" label="有效时长" width="90">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.expiryDay" type="number" v-if="showInput == `expiryDay${scope.row.productId}`"
                  @blur='blurInput(scope.row, "expiryDay", scope.row.expiryDay)' v-focus>
                </el-input>
                <span v-else style="text-decoration:none;">{{scope.row.expiryDay}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="storeName" v-if="hasRole('role:sys:super:admin')" header-align="center" align="center" label="门店名称" width="100" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="updateTime" header-align="center" align="center" label="修改时间" width="100" show-overflow-tooltip>
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="120" label="操作">
              <template slot-scope="scope">
                  <el-button size="mini" type="text" v-if="isAuth('base:baseproduct:update')"
                  @click="addOrUpdateHandle(scope.row.productId)">修改</el-button>
                <el-button size="mini" type="text" v-if="isAuth('base:baseproduct:delete')"
                  @click="deleteHandle(scope.row.productId)">删除</el-button>
               <!--   <el-dropdown size="mini" split-button type="primary" trigger="click">
                    操作
                    <el-dropdown-menu slot="dropdown"> -->
                      <!-- <el-dropdown-item v-if="isAuth('base:baseproduct:save')">
                      <el-button
                        size="mini"
                        type="success"
                        @click="saveHandle(scope.row)"
                        icon="el-icon-finished" >
                        保存</el-button>
                      </el-dropdown-item> -->
                      <!-- <el-dropdown-item v-if="isAuth('base:baseproduct:update')">
                        <el-button
                          size="mini"
                          type="primary"
                          icon="el-icon-edit"
                          @click="addOrUpdateHandle(scope.row.productId)"
                        >编辑</el-button>
                      </el-dropdown-item> -->
                      <!-- <el-dropdown-item v-if="isAuth('base:baseproduct:detail')">
                        <el-button
                          size="mini"
                          type="success"
                          @click="detailHandler(scope.row.productId)"
                          icon="el-icon-document"
                        >详情</el-button>
                      </el-dropdown-item> -->
                   <!--   <el-dropdown-item v-if="isAuth('base:baseproduct:delete')">
                        <el-button
                          type="danger"
                          icon="el-icon-delete"
                          @click="deleteHandle(scope.row.productId)"
                          size="mini"
                        >删除</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList(0)"></add-or-update>
  </div>
</template>

<script>
  import { Loading } from "element-ui"
  import AddOrUpdate from './productinfo-add-or-update'
  import {
    downLoadFile
  } from '@/utils/myUtil.js'
  export default {
    data() {
      return {
        dataForm: {
          selectField: '',
          selectValue: '',
          priceField: '',
          priceFormula: '',
          priceValue: '',
          queryField: '',
          key: '',
          unit: '',
          categoryId: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        showInput: "",
        oldData: {},
        currentData: {},
        filterText: '',
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        selectFields: [],
        priceFields: [],
        queryFields: [],
        priceFormulas: [],
        units: [],
        supplies: [],
        //导入
        upload: {
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: "导入药品数据",
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            // updateSupport: 0,
            // 设置上传的请求头部
            // 上传的地址
            url: `${window.SITE_CONFIG.baseUrl}/product/info/importData`
          },
          //上传的文件
          excelList:[],
          downCount: 0,
          downHide: 'hide',
          progressHidden: true,
          percentage: 0,
          downButtonDisabled: false,
          upPrice: 0,
          upPriceHide: 'hide',
          downPrice: 0,
          downPriceHide: 'hide'
      }
    },
    components: {
      AddOrUpdate
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    mounted() {
      this.initData()
      this.getTreeData();
      this.getUnits();
      // this.getSupplies();
      this.getDataList(0)
      this.getDownloadCount()
      this.initPrice()
    },
    methods: {
      initData() {
        let selectFields = [{
          value: 'is_rx_drug',
          label: '是否处方'
        }, {
          value: 'is_yi_bao',
          label: '是否医保'
        }, {
          value: 'is_drug',
          label: '是否中药'
        }, {
          value: 'is_split',
          label: '是否拆零药'
        }, {
          value: 'is_can_split',
          label: '能否拆零'
        }, {
          value: 'is_score',
          label: '是否积分'
        }, {
          value: 'is_discount',
          label: '是否折扣'
        }, {
          value: 'is_gift',
          label: '是否赠品'
        }, {
          value: 'is_commission',
          label: '是否提成'
        }, {
          value: 'is_first_sale',
          label: '是否首营'
        }];

        let priceFields = [{
          value: 'total_storage',
          label: '总库存'
        }, {
          value: 'profit',
          label: '毛利'
        }, {
          value: 'sale_price',
          label: '售价'
        }, {
          value: 'trade_price',
          label: '批发价'
        },{
          value: 'purchase_price',
          label: '采购价'
        }, {
          value: 'retail_price',
          label: '指导价'
        }, {
          value: 'member_price',
          label: '会员价'
        }, {
          value: 'discount_price',
          label: '折扣价'
        }, {
          value: 'top_price',
          label: '最高价'
        }, {
          value: 'lowest_price',
          label: '最低价'
        }];

        let priceFormulas = [{
          value: 'GE',
          label: '大于等于'
        }, {
          value: 'EQ',
          label: '等于'
        }, {
          value: 'GT',
          label: '大于'
        }, {
          value: 'LE',
          label: '小于等于'
        }, {
          value: 'LT',
          label: '小于'
        }, {
          value: 'NE',
          label: '不等于'
        }, ]


        let queryFields = [{
          value: 'product_code',
          label: '编码'
        }, {
          value: 'bar_code',
          label: '条形码'
        }, {
          value: 'product_name',
          label: '产品名称'
        }, {
          value: 'generic_name',
          label: '通用名'
        }, {
          value: 'pinyin',
          label: '助记码'
        }, {
          value: 'producing_area',
          label: '产地'
        }, {
          value: 'produce_factory',
          label: '厂家'
        }, {
          value: 'dosage_form',
          label: '剂型'
        }, {
          value: 'standard',
          label: '规格'
        }, {
          value: 'effect',
          label: '效果'
        }, {
          value: 'approval_no',
          label: '批准文号'
        }]

        this.selectFields = selectFields;
        this.priceFields = priceFields;
        this.priceFormulas = priceFormulas;
        this.queryFields = queryFields;
      },
      // 获取数据列表
      async getDataList(queryType) {
        this.dataListLoading = true
        const res = await this.$http({
          url: `/product/info/list`,
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'dataForm': this.dataForm,
            'queryType': (queryType ? queryType: 0)
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          this.dataList.forEach(item => {
            item.status = item.status == 1 ? true : false
          })
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList(1)
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList(1)
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      handleNodeClick(data) {
        this.dataForm.categoryId = data.id
        this.getDataList(1)
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.productId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http({
            url: `/product/info/delete`,
            method: 'post',
            data: this.$http.adornData(ids, false)
          })
          let data = res.data
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      resetForm() {
        this.$nextTick(() => {
          this.dataForm = this.$options.data().dataForm
          this.getDataList(0)
        })
      },
     async updateStatusHandle(row){
       let status = row.status ? 1 : 0
       let productId = row.productId
       const res = await this.$http({
         url: `/product/info/updateStatus/${productId}/${status}`,
         method: 'put',
       });
       let data = res.data
       if (data && data.code !== 0) {
         row.status = !row.status;
         return this.$message.error('修改失败!');
       }
       this.$message.success('更新成功！');
     },
     saveHandle(row) {
        this.$confirm(`确定保存当前的修改吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          row.status = row.status ? 1 : 0
          const res = await this.$http({
            url: `/product/info/updateById`,
            method: 'post',
            data: this.$http.adornData(row)
          });
          let data = res.data
          if (data && data.code !== 0) {
            row.status = !row.status;
            return this.$message.error('修改失败!');
          }
          this.$message.success('更新成功！');
        }).catch(() => {
            // this.$message({
            //   type: "info",
            //   message: "已取消退出"
            // });
        });
        this.getDataList()
      },
      // 当input失去光标后进行的操作
      async blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          if (value === true) {
            row[name] = 1
          } else if (value === false) {
            row[name] = 0
          }

          this.saveHandle(row)
        }
        this.showInput = ""
        this.currentData = row
      },
      tableDbEdit(row, column, event) {
        this.showInput = column.property + row.productId;
        this.oldData[column.property] = row[column.property];
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      async getUnits() {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': 'UNIT'
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.units = data.data
        }
      },
      async getSupplies() {
        let store = JSON.parse(sessionStorage.getItem("store"));
        const {
          data
        } = await this.$http({
          url: '/product/supplier/getSupplies',
          method: 'get',
          params: this.$http.adornParams({
            'storeId': store ? store.storeId : null
          })
        })
        if (data && data.code === 0) {
          this.supplies = data.data
        }
      },
      async getTreeData() {
        const res = await this.$http({
          url: '/product/category/getTreeData',
          method: 'get',
        })
        let data = res.data
        if (data && data.code === 0) {
          this.treeData = data.data
        }
      },
      async exportData(type) {
        const res = await this.$http({
          url: `/product/info/exportData?type=`+ type,
          method: 'get',
          responseType: 'blob',
          params: this.$http.adornParams()
        });
        downLoadFile(res)
      },
      beforeUpload(file) {
         //截取文件后缀名
         const fileName = file.name.substring(file.name.lastIndexOf('.'));
         if(fileName.toLowerCase()!='.xls' && fileName.toLowerCase() !='.xlsx'){
           this.$message.error('文件必须为.xls或xlsx类型');
           this.fileList = [];
           return false;
         };
         //读取文件大小
         var fileSize = file.size;
         if(fileSize > 3249576){
           this.uploadShowDialog = false;
           this.$message({
             type:'error',
             showClose:true,
             duration:3000,
             message:'文件不能大于3M!'
           });
           return false;
         }
      },
      // excel表上传
      handleUploadChange(file, fileList) {
         if (fileList.length > 0) {
         // 这一步，是展示最后一次选择的文件
         this.fileList = [fileList[fileList.length - 1]];    }
       },
       //导入按钮
       handleImport(){
         this.upload.open = true;
       },
       //导入提交
       async submitFileForm(){
         if (this.excelList.length === 0) {
           this.$message.warning("请选择文件");
           return;
         }
         if (this.excelList.length > 1) {
           this.$message.warning("每次只能提交一个文件");
           return;
         }
         let formData = new FormData();
         this.excelList.forEach((item) => {
           formData.append("file", item.raw);
         });
         let loadingInstance = Loading.service({
           lock: true, //lock的修改符--默认是false
           text: "导入中", //显示在加载图标下方的加载文案
           spinner: "el-icon-loading", //自定义加载图标类名
           background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
           target: document.querySelector("#futureTransferDialog"), //loadin覆盖的dom元素节点
         });
         const res = await this.$http({
           url: this.upload.url,
           method: 'post',
           data: formData
         })
         let data = res.data
         if (data && data.code === 0) {
           loadingInstance.close();
           this.$message({
             type: "success",
             message: "导入成功!",
           });
           this.getDataList();
         }
         this.excelList = [];
         this.upload.open = false;
         loadingInstance.close();
         this.dataListLoading = false
       },
       //下载导入模板
       downloadImportTemplate(){
         window.location.href = "http://file.asdzy.com/upload/files/film/药品模板.xlsx"
       },
     // 文件上传成功处理
       handleFileSuccess(response, file, fileList) {
         this.excelList = fileList;
       },
     // 文件上传中处理
       handleFileUploadProgress(event, file, fileList) {
         this.upload.isUploading = true;
       },
       onChangeDr(file, fileList) {
         this.excelList = fileList;
       },
       onRemoveDr(file, fileList) {
         this.excelList = fileList;
       },
       cancelFileForm(){
         this.upload.open = false
         this.excelList = [];
       },
       async getDownloadCount(){  /**检查是否有新商品数据下载*/
          const res = await this.$http({
            url: '/product/info/getDownloadCount',
            method: 'get',
          })
          let data = res.data
          if (data && data.code === 0) {
            if(data.data > 0){
              let count = data.data;
              if(count > 99){
                count = "99+";
              }
              this.downCount = count;
              this.downHide = 'show'
            }else{
              this.downCount = 0;
              this.downHide = 'hide'
            }
          }
        },
        async downloadDataHandle(){
          this.progressHidden = false
          this.downButtonDisabled = true
          const res = await this.$http({
            url: '/product/info/downloadProductFromCenter',
            method: 'get',
          })
          this.percentage = 100
          let data = res.data
          this.progressHidden = true
          this.downButtonDisabled = false
          this.getDataList()
        },
        initPrice(){
          this.handleDownPrice()
          this.handleUpPrice()
        },
        async handleUpPrice(){
          let priceType = 1
          const res = await this.$http({
            url: `/product/info/getPriceCount/${priceType}`,
            method: 'get',
          })
          let data = res.data
          if (data && data.code === 0) {
            if(data.data > 0){
              let count = data.data;
              if(count > 99){
                count = "99+";
              }
              this.upPrice = res.data.data
              this.upPriceHide = 'show'
            }else{
              this.upPrice = 0
              this.upPriceHide = 'hide'
            }
          }
        },
        async handleDownPrice(){
          let priceType = 0
          const res = await this.$http({
            url: `/product/info/getPriceCount/${priceType}`,
            method: 'get',
          })
          let data = res.data
          if (data && data.code === 0) {
            if(data.data > 0){
              let count = data.data;
              if(count > 99){
                count = "99+";
              }
              this.downPrice = res.data.data
              this.downPriceHide = 'show'
            }else{
              this.downPrice = 0
              this.downPriceHide = 'hide'
            }
          }
        }
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
<style lang="less" scoped>
  .filter-tree {
    background-color: white;
  }
  .el-col:nth-child(2) {
    padding-left: 20px;
  }
  .el-select {
    max-width: 100px;
  }
  .el-input {
    margin: 0px;
  }
  .el-dropdown-menu--mini .el-dropdown-menu__item {
      line-height: 32px;
  }
  .file-uploader{
    margin-left: 10px;
    display: inline;
  }
  .el-button{
    position: relative;
  }
</style>
